package com.example.userservice.interceptor;

import com.example.userservice.common.UserContext;
import com.example.userservice.entity.dto.UserDto;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import com.example.userservice.util.JwtUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                throw new RuntimeException("无效的token");
            }

            String token = authHeader.substring(7);
            Claims claims = JwtUtil.parseToken(token);
            String username = claims.get("username", String.class);
            Long userId = claims.get("userId", Long.class);

            if (userId == null || username == null) {
                throw new RuntimeException("Token缺少必要信息");
            }

            UserContext.set(new UserDto(username, userId));

            return true;
        } catch (Exception e) {
            System.out.println("JWT拦截器错误：" + e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期\"}");
            return false;
        }
    }

}
